import React, { Component } from 'react';
import {Upload,Button, Icon, message, Progress, List} from 'antd';
import axios from 'axios';


class UploadBlock extends Component {
    constructor(props) {
        super(props);
        this.state = {
            fileList: [],
            uploading: false,
            isShowProcess: false,
            uploadError: [],
            process: 0,
            filename: '',
            chunkSize: 1024 * 1024 * 3, //分片上传每片3MB
            isSuccess: false,
            fileLength: 0,
            fileAllSize: 0,
            fileType:false,
            uploadUrl: `${window.uploadUrl}/api/upload/video`
        };

        this.handleUpload = this.handleUpload.bind(this);
        this.handleModalClose = this.handleModalClose.bind(this);
        this.handelModalCancel = this.handelModalCancel.bind(this);
        this.handleFileUpload = this.handleFileUpload.bind(this);
        this.handleSingleUpload = this.handleSingleUpload.bind(this);
        this.handleUploadAfter = this.handleUploadAfter.bind(this);

    }

    async handleUpload() {
        if(this.state.fileType !== "video/mp4")
        {
            message.error('只允许上传mp4');
            return;
        }
        const { fileList } = this.state;
        this.setState({ uploading: true, isShowProcess: true });

        for (let i = 0; i < fileList.length; i++) {
            this.setState({ isShowProcess: true, filename: fileList[i].name, process: 0 });

            if (fileList[i].size > this.state.chunkSize) {
                await this.handleFileUpload(fileList[i]);    //分片上传
            } else {
                await this.handleSingleUpload(fileList[i]);  //单个上传
            }
        }

        message.success('全部文件上传完毕');
        this.setState({ uploading: false, isShowProcess: false });
        this.handleUploadAfter();
    };

    async handleSingleUpload(file)
    {
        let formData = new FormData();
        formData.append("file", file, file.name);
        formData.append("name", file.name);
        formData.append("size", this.state.fileAllSize);

        this.setState({ process: 99 });

        try {
            await axios.post(this.state.uploadUrl, formData);
            this.setState({ isSuccess: true });
        } catch (error) {
            this.setState(({ uploadError }) => {
                uploadError.push([file.name])
            });
        }

        this.setState(({ fileList }) => {
            const index = fileList.indexOf(file);
            const newFileList = fileList.slice();
            newFileList.splice(index, 1);
            return {
                fileList: newFileList,
            };
        });
    }

    async handleFileUpload(file)
    {
        let chunkNum;
        let start = 0;
        let end;
        let index = 0;
        let filename = file.name;
        let fileSize = file.size;

        //计算文件切片总数
        chunkNum = Math.ceil(file.size / this.state.chunkSize);

        let timestamp = (new Date()).getTime();
        while (start < file.size) {
            end = start + this.state.chunkSize;

            if(end > file.size) {
                end = file.size;
            }

            let chunk = file.slice(start, end);
            let formData = new FormData();
            formData.append("file", chunk, filename);
            formData.append("chunks", chunkNum);
            formData.append("chunk", index);
            formData.append("lastModifiedDate", timestamp);
            formData.append("size", fileSize);
            formData.append("name", filename);

            try {
                await axios.post(this.state.uploadUrl, formData);
                let process = Math.floor((index + 1) / chunkNum * 100);
                this.setState({ process: process });
            } catch (e) {
                this.setState(({ uploadError }) => {
                    uploadError.push([filename])
                });
                return false;
            }

            start = end;
            index++;
        }


        this.setState(({ fileList }) => {
            const index = fileList.indexOf(file);
            const newFileList = fileList.slice();
            newFileList.splice(index, 1);
            return {
                fileList: newFileList,
            };
        });
    }

    handleModalClose = () => {
        this.setState({
            fileList: [],
            uploading: false,
            isShowProcess: false,
            process: 0,
            uploadError: [],
            isSuccess: false,
            fileLength: 0
        })
    };

    handelModalCancel = () => {
        this.props.onCancel(this.state.isSuccess);
        this.setState({
            fileList: [],
            uploading: false,
            isSuccess: false,
            fileLength: 0
        })
    };

    handleUploadAfter = () => {
        if (this.props.record) {
            this.props.onOk();
        }
    };

    render() {

        const Dragger = Upload.Dragger;
        const uploadConfig = {
            name: 'file',
            multiple: true,
            action: this.state.uploadUrl,
            onRemove: (file) => {
                this.setState(({ fileList }) => {
                    const index = fileList.indexOf(file);
                    const newFileList = fileList.slice();
                    newFileList.splice(index, 1);
                    return {
                        fileList: newFileList,
                    };
                });
                this.setState({
                    fileLength: 0
                });
            },
            beforeUpload: (file) => {
                console.log(file)
                this.setState({
                    fileType:file.type
                },()=>{
                    if(this.state.fileType !== "video/mp4")
                    {
                        message.error('只允许上传mp4');
                        return;
                    }

                    this.setState(({ fileList }) => ({
                        fileList: [...fileList, file],
                        fileAllSize: parseInt(file.size)
                    }));
                });

                return false;
            },

            fileList: this.state.fileList,
        };


        return (
            <div>
                <Dragger {...uploadConfig}>
                    <p className="ant-upload-drag-icon">
                        <Icon type="inbox" />
                    </p>
                    <p className="ant-upload-text">Click or drag file to this area to upload</p>
                    <p className="ant-upload-hint">Support for a single or bulk upload. Strictly prohibit from uploading company data or other band files</p>
                </Dragger>
                {
                    this.state.isShowProcess === true ?
                        <span>
                        {this.state.filename} 上传中
                        <Progress percent={this.state.process} status="active"/>
                    </span> : ''
                }

                {
                    this.state.uploadError.length > 0 ?
                        <div>
                            <List
                                size="small"
                                header={<div>上传失败的文件</div>}
                                dataSource={this.state.uploadError}
                                renderItem={item => (<List.Item style={{color:"red"}}>{item}</List.Item>)}
                            />
                        </div> : ''
                }
                <Button
                    style={{marginTop:"16px", width:"100%"}}
                    type="primary"
                    onClick={this.handleUpload}
                    disabled={this.state.fileList.length === 0}
                    loading={this.state.uploading}
                >
                    {this.state.uploading ? '上传中' : '确认上传' }
                </Button>

            </div>
        );
    }
}

export default UploadBlock;
